<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>后台管理</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(to right, #2c3e50, #3498db);
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
        }

        .sidebar {
            width: 250px;
            background: #34495e;
            color: #fff;
            padding: 20px;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }

        .sidebar h2 {
            text-align: center;
            margin-top: 0;
        }

        .sidebar a {
            display: block;
            padding: 10px;
            margin: 10px 0;
            color: #fff;
            text-decoration: none;
            border-radius: 5px;
            transition: background 0.3s;
        }

        .sidebar a:hover {
            background: #2980b9;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        h1, h2 {
            color: #fff;
        }

        form {
            width: 100%;
            max-width: 500px;
            margin: 20px 0;
            padding: 20px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        form label {
            display: block;
            margin: 10px 0 5px;
        }

        form input, form select, form textarea, form button {
            width: calc(100% - 20px);
            padding: 10px;
            margin: 5px 0 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }

        form button {
            background: #3498db;
            color: #fff;
            border: none;
            cursor: pointer;
        }

        form button:hover {
            background: #2980b9;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        table th, table td {
            padding: 10px;
            border: 1px solid #ccc;
            text-align: left;
        }

        table th {
            background: #3498db;
            color: #fff;
        }

        table tr:nth-child(even) {
            background: #f9f9f9;
        }

        .actions button {
            background: #e74c3c;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            padding: 5px 10px;
            margin: 2px;
        }

        .actions button:hover {
            background: #c0392b;
        }

        .hidden {
            display: none;
        }
       
    </style>
</head>
<body>
    <div class="sidebar">
        <h2>后台管理</h2>
        <a href="#" onclick="showSection('userManagementAdd')">新增用户</a>
        <a href="#" onclick="showSection('userManagementList')">所有用户</a>
        <a href="#" onclick="showSection('announcementAdd')">新增公告</a>
        <a href="#" onclick="showSection('announcementList')">所有公告</a>
    </div>

    <div class="content">
        <div id="userManagementAdd" class="hidden">
            <h1>用户管理</h1>

            <h2>新增用户</h2>
            <form id="addUserForm">
                <label for="username">用户名:</label>
                <input type="text" id="username" name="username" required>
                <br>
                <label for="password">密码:</label>
                <input type="password" id="password" name="password" required>
                <br>
                <label for="role">角色:</label>
                <select id="role" name="role">
                    <option value="user">用户</option>
                    <option value="admin">审核</option>
                </select>
                <br>
                <button type="submit">新增</button>
            </form>
        </div>

        <div id="userManagementList" class="hidden">
            <h1>用户管理</h1>

            <h2>所有用户</h2>
            <table id="userTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>

        <div id="announcementAdd" class="hidden">
            <h1>公告发布</h1>

            <h2>新增公告</h2>
            <form id="addAnnouncementForm">
                <label for="announcementTitle">公告标题:</label>
                <input type="text" id="announcementTitle" name="title" required>
                <br>
                <label for="announcementContent">公告内容:</label>
                <textarea id="announcementContent" name="content" rows="4" required></textarea>
                <br>
                <button type="submit">发布</button>
            </form>
        </div>

        <div id="announcementList" class="hidden">
            <h1>公告发布</h1>

            <h2>所有公告</h2>
            <table id="announcementTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>内容</th>
                        <th>发布时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <script>
        function showSection(sectionId) {
            const sections = document.querySelectorAll('.content > div');
            sections.forEach(section => {
                section.classList.add('hidden');
            });
            document.getElementById(sectionId).classList.remove('hidden');
        }

        document.addEventListener('DOMContentLoaded', function() {
            const userTableBody = document.getElementById('userTable').getElementsByTagName('tbody')[0];
            const addUserForm = document.getElementById('addUserForm');
            const announcementTableBody = document.getElementById('announcementTable').getElementsByTagName('tbody')[0];
            const addAnnouncementForm = document.getElementById('addAnnouncementForm');

            function fetchUsers() {
                fetch('user_api.php')
                    .then(response => response.json())
                    .then(users => {
                        userTableBody.innerHTML = '';
                        users.forEach(user => {
                            const row = userTableBody.insertRow();
                            row.insertCell(0).textContent = user.id;
                            row.insertCell(1).textContent = user.username;
                            row.insertCell(2).textContent = user.role;

                            const actionsCell = row.insertCell(3);
                            const editButton = document.createElement('button');
                            editButton.textContent = '编辑';
                            editButton.onclick = () => showEditForm(user.id, user.role);
                            actionsCell.appendChild(editButton);

                            const deleteButton = document.createElement('button');
                            deleteButton.textContent = '删除';
                            deleteButton.onclick = () => deleteUser(user.id);
                            actionsCell.appendChild(deleteButton);
                        });
                    });
            }
            

            function fetchAnnouncements() {
                fetch('announcement_api.php')
                    .then(response => response.json())
                    .then(announcements => {
                        announcementTableBody.innerHTML = '';
                        announcements.forEach(announcement => {
                            const row = announcementTableBody.insertRow();
                            row.insertCell(0).textContent = announcement.id;
                            row.insertCell(1).textContent = announcement.title;
                            row.insertCell(2).textContent = announcement.content;
                            row.insertCell(3).textContent = announcement.created_at;

                            const actionsCell = row.insertCell(4);
                            const deleteButton = document.createElement('button');
                            deleteButton.textContent = '删除';
                            deleteButton.onclick = () => deleteAnnouncement(announcement.id);
                            actionsCell.appendChild(deleteButton);
                        });
                    });
            }

            function showEditForm(userId, currentRole) {
                const editForm = document.createElement('form');
                editForm.innerHTML = `
                    <label for="editRole">角色:</label>
                    <select id="editRole" name="role">
                        <option value="user" ${currentRole === 'user' ? 'selected' : ''}>用户</option>
                        <option value="admin" ${currentRole === 'admin' ? 'selected' : ''}>审核</option>
                    </select>
                    <button type="submit">保存</button>
                `;

                editForm.onsubmit = (event) => {
                    event.preventDefault();
                    const role = editForm.role.value;
                    editUser(userId, role);// 调用编辑用户角色的函数
                };

                const row = Array.from(userTableBody.rows).find(row => row.cells[0].textContent == userId);
                row.cells[2].innerHTML = '';// 清空角色单元格内容
                row.cells[2].appendChild(editForm);// 将编辑表单添加到角色单元格中
            }

            function addUser(username, password, role) {
                var hashedPassword = CryptoJS.SHA256(password).toString();
                fetch('user_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, hashedPassword, role })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('添加成功！');
                        fetchUsers();
                    } else {
                        alert('添加失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('发生错误: ' + error.message);
                });
            }

            function editUser(userId, role) {
                fetch('user_api.php', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: userId, role })
                })
                .then(response => response.json())
                .then(() => fetchUsers()) // 更新用户列表显示
                .catch(error => {
                    alert('编辑用户失败: ' + error.message);
                });
            }

            function deleteUser(userId) {
                fetch('user_api.php', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: userId })
                })
                .then(response => response.json())
                .then(() => fetchUsers());
            }

            function addAnnouncement(title, content) {
                fetch('announcement_api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ title, content })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('发布成功!');
                        fetchAnnouncements();
                    } else {
                        alert('发布失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('发生错误: ' + error.message);
                });
            }

            function deleteAnnouncement(announcementId) {
                fetch('announcement_api.php', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: announcementId })
                })
                .then(response => response.json())
                .then(() => fetchAnnouncements());
            }

            addAnnouncementForm.onsubmit = (event) => {
                event.preventDefault();
                const formData = new FormData(addAnnouncementForm);
                const title = formData.get('title');
                const content = formData.get('content');
                addAnnouncement(title, content);
                addAnnouncementForm.reset();
            };

            addUserForm.onsubmit = (event) => {
                event.preventDefault();
                const formData = new FormData(addUserForm);
                const username = formData.get('username');
                const password = formData.get('password');
                const role = formData.get('role');
                addUser(username, password, role);
                addUserForm.reset();
            };

            fetchUsers();
            fetchAnnouncements();
        });
    </script>
</body>
</html>
